<template>
  <el-card>
    <el-form inline class="form">
      <el-form-item label="用户名">
        <el-input placeholder="请输入用户名" v-model="keyword"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :disabled="!keyword" @click="onSearch">
          搜索
        </el-button>
        <el-button type="primary" @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0">
    <el-button type="primary" icon="Plus" @click="onAddUser">
      添加用户
    </el-button>
    <el-button
      type="danger"
      icon="Delete"
      :disabled="selectIdArr.length === 0"
      @click="onDeleteSelectUser"
    >
      批量删除
    </el-button>
    <el-table
      style="margin: 20px 0"
      border
      stripe
      :data="userArr"
      @selection-change="selectChange"
    >
      <el-table-column type="selection" width="50px"></el-table-column>
      <el-table-column
        label="#"
        align="center"
        width="100px"
        type="index"
      ></el-table-column>
      <el-table-column
        label="ID"
        align="center"
        width="100px"
        prop="id"
      ></el-table-column>
      <el-table-column
        label="用户账号"
        align="center"
        width="150px"
        prop="username"
      ></el-table-column>
      <el-table-column
        label="用户名称"
        align="center"
        width="150px"
        prop="name"
      ></el-table-column>
      <el-table-column
        label="用户角色"
        align="center"
        width="100px"
        prop="roleName"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="操作" align="center" width="300px" fixed="right">
        <template #="{ row, index }">
          <el-button
            type="success"
            size="small"
            icon="User"
            @click="onSetRole(row)"
          >
            分配角色
          </el-button>
          <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="onEditUser(row)"
          >
            编辑
          </el-button>
          <el-popconfirm
            :title="`你确定要删除${row.username}？`"
            width="260px"
            @confirm="onDeleteUser(row.id)"
          >
            <template #reference>
              <el-button type="danger" size="small" icon="Delete">
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--分页器-->
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :background="true"
      :page-sizes="[10, 20, 30, 40]"
      layout=" prev, pager, next, jumper,->, sizes,total"
      :total="total"
      @current-change="getHasUser"
      @size-change="handler"
    />
  </el-card>
  <!--新增用户、修改用户的抽屉-->
  <el-drawer v-model="drawer">
    <template #header>
      <h4>{{ userParams.id ? '更新用户' : '添加用户' }}</h4>
    </template>
    <template #default>
      <el-form :model="userParams" :rules="rules" ref="formRef">
        <el-form-item label="用户账号" prop="username">
          <el-input
            placeholder="请输入用户账号"
            v-model="userParams.username"
          />
        </el-form-item>
        <el-form-item label="用户昵称" prop="name">
          <el-input placeholder="请输入用户昵称" v-model="userParams.name"/>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
          <el-input
            placeholder="请输入用户密码"
            v-model="userParams.password"
          />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button type="primary" @click="onCancel">取消</el-button>
      <el-button type="primary" @click="onSave">确定</el-button>
    </template>
  </el-drawer>
  <!--角色分配的抽屉-->
  <el-drawer v-model="drawer1">
    <template #header>
      <h4>分配角色(职位)</h4>
    </template>
    <template #default>
      <el-form label-width="100px">
        <el-form-item label="用户昵称">
          <el-input v-model="userParams.username" disabled/>
        </el-form-item>
        <el-form-item label="职位列表">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="onCheckAll"
          >
            全选
          </el-checkbox>
          <!--职位复选框-->
          <el-checkbox-group v-model="userRole">
            <el-checkbox
              v-for="(role, index) in allRoleList"
              :key="index"
              :label="role"
              @change="onCheckRole"
            >
              {{ role.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button type="primary" @click="drawer1 = fales">取消</el-button>
      <el-button type="primary" @click="onConfirm">确定</el-button>
    </template>
  </el-drawer>
</template>
<script setup lang="ts">
import {nextTick, onMounted, reactive, ref} from 'vue'
import {
  reqAddOrUpdateUser,
  reqAllRole,
  reqRemoveUser,
  reqSelectUser,
  reqSetUserRole,
  reqUserInfo,
} from '@/api/acl/user'
import type {
  AllRole,
  AllRoleResponseData,
  Records,
  SetRoleData,
  User,
  UserResponseData,
} from '@/api/acl/user/type'
import {ElMessage} from 'element-plus'
import useLayoutSettingStore from '@/store/modules/setting.ts'

// 用户输入的文字
let keyword = ref<string>('')
let pageNo = ref<number>(1)
let pageSize = ref<number>(10)
let total = ref<number>(0)
// 存储全部用户
let userArr = ref<Records>([])
// 控制新增或修改用户的抽屉显示、隐藏
let drawer = ref<boolean>(false)
// 控制角色分配的抽屉显示、隐藏
let drawer1 = ref<boolean>(false)
// 收集用户信息
const userParams = reactive<User>({
  username: '',
  name: '',
  password: '',
})
// 获取form组件实例
let formRef = ref<any>()
// 存储全部职位的数据
let allRoleList = ref<AllRole>([])
// 当前用户已有的职位
let userRole = ref<AllRole>([])
// 全选复选框
let checkAll = ref<boolean>(false)
// 全选复选框不确定样式
const isIndeterminate = ref<boolean>(true)
// 批量删除的用户
let selectIdArr = ref<User>([])
// 获取模板仓库
let settingStore = useLayoutSettingStore()

onMounted(() => {
  getHasUser()
})
// 校验用户账号
const validatorUserName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 5) {
    callBack()
  } else {
    callBack(new Error('用户账号长度至少五位'))
  }
}
// 校验用户名字
const validatorName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 5) {
    callBack()
  } else {
    callBack(new Error('用户昵称长度至少五位'))
  }
}
// 校验用户密码
const validatorPassword = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 6) {
    callBack()
  } else {
    callBack(new Error('用户密码长度至少六位'))
  }
}
// 表单校验规则
const rules = {
  username: [{required: true, trigger: 'blur', validator: validatorUserName}],
  name: [{required: true, trigger: 'blur', validator: validatorName}],
  password: [{required: true, trigger: 'blur', validator: validatorPassword}],
}
// 获取全部用户信息
const getHasUser = async (pager = 1) => {
  pageNo.value = pager
  let result: UserResponseData = await reqUserInfo(
    pageNo.value,
    pageSize.value,
    keyword.value,
  )
  if (result.code === 200) {
    total.value = result.data.total
    userArr.value = result.data.records
  }
}
// 切换条数
const handler = () => {
  getHasUser()
}
// 点击新增用户
const onAddUser = () => {
  drawer.value = true
  // 清空数据
  Object.assign(userParams, {
    id: 0,
    username: '',
    name: '',
    password: '',
  })
  // 清除表单验证提示
  nextTick(() => {
    formRef.value.clearValidate('userName')
    formRef.value.clearValidate('name')
    formRef.value.clearValidate('password')
  })
}
// 点击批量删除
const onDeleteSelectUser = async () => {
  let idList: any = selectIdArr.value.map((item: { id: number }) => {
    return item.id
  })
  let result: any = await reqSelectUser(idList)
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    await getHasUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
  }
}
// 点击分配角色
const onSetRole = async (row: User) => {
  Object.assign(userParams, row)
  // 获取全部职位和当前账号已有的职位
  let result: AllRoleResponseData = await reqAllRole(userParams.id)
  if (result.code === 200) {
    // 存储全部的职位
    allRoleList.value = result.data.allRolesList
    // 存储当前用户已有的职位
    userRole.value = result.data.assignRoles
    // 显示抽屉
    drawer1.value = true
  }
}
// 点击编辑用户
const onEditUser = (row: User) => {
  // 清除表单验证提示
  nextTick(() => {
    formRef.value.clearValidate('userName')
    formRef.value.clearValidate('name')
  })
  drawer.value = true
  Object.assign(userParams, row)
}
// 点击删除用户
const onDeleteUser = async (id: number) => {
  let result = await reqRemoveUser(id)
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    await getHasUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
  }
}
// 点击确定
const onSave = async () => {
  // 表单校验
  await formRef.value.validate()
  let result: any = await reqAddOrUpdateUser(userParams)
  if (result.code === 200) {
    drawer.value = false
    ElMessage({
      type: 'success',
      message: userParams.id ? '更新成功' : '添加成功',
    })
    // await getHasUser(userParams.id ? pageNo.value : 1)
    window.location.reload()
  } else {
    drawer.value = false
    ElMessage({
      type: 'error',
      message: userParams.id ? '更新失败' : '添加失败',
    })
  }
}
// 点击取消
const onCancel = () => {
  drawer.value = false
}
// 点击全选复选框
const onCheckAll = (val: boolean) => {
  userRole.value = val ? allRoleList.value : []
  isIndeterminate.value = false
}
// 点击职位复选框
const onCheckRole = (value: string[]) => {
  checkAll.value = value.length === allRoleList.value.length
  isIndeterminate.value = value.length !== allRoleList.value.length
}
// 点击职位抽屉的缺点
const onConfirm = async () => {
  let data: SetRoleData = {
    userId: userParams.id,
    roleIdList: userRole.value.map((item: { id: number }) => item.id),
  }
  let result = await reqSetUserRole(data)
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: '修改成功',
    })
    drawer1.value = false
    await getHasUser(pageNo.value)
  }
}
// 点击table复选框
const selectChange = (value: any) => {
  selectIdArr.value = value
}
// 点击搜索
const onSearch = () => {
  getHasUser()
  keyword.value = ''
}
// 点击重置
const onReset = () => {
  settingStore.refresh = !settingStore.refresh
}
</script>
<style scoped lang="scss">
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
